//
//  YYmassAddVC.m
//  jkljlkjlk
//
//  Created by 杨毅 on 17/1/22.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "YYmassAddVC.h"

@interface YYmassAddVC ()
{
    NSString *_time;//当前时间
    NSInteger userID;
    NSInteger equipID;
}

@property(nonatomic,strong)AFHTTPSessionManager *manager;
@property(nonatomic,strong)MassMessageView *masview;
@property(nonatomic,strong)NSMutableArray *EquipNameArray;
@property(nonatomic,strong)NSMutableArray *dataSource;//设备数据
@property(nonatomic,strong)NSDictionary *dataDictionary;//其他数据
@end

@implementation YYmassAddVC
- (AFHTTPSessionManager  *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self EquipmentNetworking];
}
- (void)EquipmentNetworking{
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:EquipURL parameters:@{@"stationId":[NSString stringWithFormat:@"%ld",self.stationId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.EquipNameArray removeAllObjects];
        [self.dataSource removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        XJEqDataModel *datamodel = [[XJEqDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (XJEqListModel *model in datamodel.Equiplist) {
            [self.EquipNameArray addObject:model.equipName];
            [self.dataSource addObject:model];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"质量信息报告单";
    //NSSLog(@"%ld",(long)self.stationId);
    self.EquipNameArray = [[NSMutableArray alloc]init];
    self.dataSource = [[NSMutableArray alloc]init];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIScrollView *scroller = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-63)];
    scroller.showsHorizontalScrollIndicator = NO;
    scroller.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scroller];
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *dele = app.delegate;
    userID = dele.userId;
    _dataDictionary = @{@"pson":dele.username,@"tel":dele.tel,@"adderss":self.address,@"custmeN":self.custName};
    self.masview = [[MassMessageView alloc]initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 580) AndDataDictionary:_dataDictionary];
    self.masview.delegate = self;
    [scroller addSubview:self.masview];
    scroller.contentSize = CGSizeMake(kSCREEN_WIDTH, 645);
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    //[dateFormatter stringFromDate:currentDate];
    UILabel *BSlab = [[UILabel alloc]initWithFrame:CGRectMake(-2, kSCREEN_HEIGHT-60, kSCREEN_WIDTH/3+2, 63)];
    BSlab.backgroundColor = [UIColor whiteColor];
    BSlab.text = [NSString stringWithFormat:@"报送人:%@\n日期:%@",dele.username,[dateFormatter stringFromDate:currentDate]];
    BSlab.layer.borderColor = UIColorFromRGB(0x0093d5).CGColor;
    BSlab.layer.borderWidth = 1.0f;
    BSlab.layer.cornerRadius = 5;
    BSlab.font = [UIFont systemFontOfSize:13.0];
    BSlab.textColor = UIColorFromRGB(0x4d4d4d);
    BSlab.numberOfLines = 0;
    BSlab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:BSlab];
    UILabel *TechniLab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(BSlab.frame), kSCREEN_HEIGHT-58, kSCREEN_WIDTH/3, 60)];
    TechniLab.backgroundColor = [UIColor whiteColor];
    TechniLab.text = @" 技术支持签收人:\n 日期:";
    TechniLab.layer.borderColor = UIColorFromRGB(0xb6b6b6).CGColor;
    TechniLab.layer.borderWidth = 1.0f;
    TechniLab.font = [UIFont systemFontOfSize:13.0];
    TechniLab.textColor = UIColorFromRGB(0xbfbfc4);
    TechniLab.numberOfLines = 0;
    TechniLab.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:TechniLab];
    UILabel *MassLab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(TechniLab.frame), kSCREEN_HEIGHT-58, kSCREEN_WIDTH/3+1, 60)];
    MassLab.backgroundColor = [UIColor whiteColor];
    MassLab.text = @" 品质部签收人:\n 日期";
    MassLab.layer.borderColor = UIColorFromRGB(0xb6b6b6).CGColor;
    MassLab.layer.borderWidth = 1.0f;
    MassLab.font = [UIFont systemFontOfSize:13.0];
    MassLab.textColor = UIColorFromRGB(0xbfbfc4);
    MassLab.numberOfLines = 0;
    MassLab.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:MassLab];
}

#pragma mark MassMessageViewDelegate
- (void)FinderTimeChoose:(UIButton *)sender{
    FDAlertView *alert = [[FDAlertView alloc] init];
    
    RBCustomDatePickerView * contentView=[[RBCustomDatePickerView alloc]init];
    contentView.delegate=self;
    contentView.frame = CGRectMake(0, 0, 320, 300);
    alert.contentView = contentView;
    [alert show];
}
//RBCustomDatePickerView 的代理方法
-(void)getTimeToValue:(NSString *)theTimeStr
{
    [self.masview.FinderTimeBtn setTitle:theTimeStr forState:UIControlStateNormal];
    [self.masview.FinderTimeBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
    //NSLog(@"我获取到时间了，时间是===%@",theTimeStr);
}
- (void)ProductChoose:(UIButton *)sender{
    
    MHActionSheet *sheet = [[MHActionSheet alloc]initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:self.EquipNameArray];
    __weak typeof(self) weakSelf = self;
    [sheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
        XJEqListModel *model = weakSelf.dataSource[index];
        [weakSelf.masview.ChooseProductBTN setTitle:model.equipName forState:UIControlStateNormal];
        [weakSelf.masview.ChooseProductBTN setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        weakSelf.masview.EquipeNum.text = model.code;
        weakSelf.masview.MonitorType.text = model.stationType;
        weakSelf.masview.ProductModel.text = model.equipmodel;
        equipID = model.equipId;
    }];
}
#pragma mark MassMessageViewDelegate --->图片代理
- (void)MasViewAddAndSetSubViews:(KKUploadPhotoCollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath{
    //清空子控件,解决重用问题
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    UIImageView *imageView = [[UIImageView alloc]init];
    [cell.contentView addSubview:imageView];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    cell.tag = 11; //根据tag值设定是否可点击,11可点击,初始全部可点击
    cell.imageView = imageView;
    cell.backgroundColor = [UIColor whiteColor];
    if(indexPath.row == self.masview.imageArray.count){
        imageView.image = [UIImage imageNamed:@"add"];
    }else{
        imageView.image = nil;
    }
    
    UIButton *cancleBtn = [[UIButton alloc]init];
    cell.cancleBtn = cancleBtn;
    [cell.contentView addSubview: cancleBtn];
    [cancleBtn setImage:[UIImage imageNamed:@"circle_delete"] forState:UIControlStateNormal];
    cancleBtn.hidden = YES;//初始将删除按钮隐藏
    cell.cancleBtn.tag = indexPath.row;
    [cell.cancleBtn addTarget:self action:@selector(cancleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.imageView.frame = CGRectMake(0, 0, 80, 80);
    cell.cancleBtn.frame = CGRectMake(60, 0, 20, 20);
    
    if (self.masview.imageArray.count > indexPath.row) {
        if ([self.masview.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.imageView.image = nil;
            cell.imageView.image = self.masview.imageArray[indexPath.row];
            cell.cancleBtn.hidden = NO;
            cell.tag = 10; //初始设置tag为11,当为10时,表示已经添加图片
        }
    }
}
#pragma mark  删除图片
- (void)cancleBtnClick:(UIButton *)sender{
    if (sender.tag < self.masview.imageArray.count) {
        [self.masview.imageArray removeObjectAtIndex:sender.tag];
        sender.hidden = YES;
        [self.masview.collectionView reloadData];
    }
}
- (void)MasViewCollectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView cellForItemAtIndexPath:indexPath].tag == 11) {
        [[KKPhotoPickerManager shareInstace] showActionSheetInView:self.view fromController:self completionBlock:^(NSMutableArray *imageArray) {
            for (int i = 0; i<imageArray.count; i++) {
                if (self.masview.imageArray.count < 5) {
                    UIImage *image = imageArray[i];
                    [self.masview.imageArray addObject:image]; //上传图片保存到数组
                }
            }
            [self.masview.collectionView reloadData];
        }];
    }
}
- (void)upBtnClick:(UIButton *)sender{
    
    [UIView animateWithDuration:0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        self.masview.UpBtn.userInteractionEnabled = NO;
    } completion:^(BOOL finished) {
        self.masview.UpBtn.userInteractionEnabled = YES;
    }];
    
    //NSSLog(@"%ld",equipID);
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    _time = [dateFormatter stringFromDate:currentDate];
    

    NSDictionary *premert = @{@"userId":[NSString stringWithFormat:@"%ld",userID],@"time":self.masview.FinderTimeBtn.titleLabel.text,@"equipId":[NSString stringWithFormat:@"%ld",equipID],@"num":self.masview.NumberTF.text,@"faultDisc":self.masview.GuzhangTF.text,@"discrib":self.masview.DiscribTextView.text,@"equipName":self.masview.ChooseProductBTN.titleLabel.text,@"receiveTime":_time};
    if ([self.masview.FinderTimeBtn.titleLabel.text isEqualToString:@"选择时间"] || self.masview.GuzhangTF.text.length < 1 || self.masview.DiscribTextView.text.length < 1 || [self.masview.ChooseProductBTN.titleLabel.text isEqualToString:@"选择产品"]) {
            [self showAlert:@"温馨提示" message:@"请完善提交信息" actionWithTitle:@"我知道了"];
    }else if (self.masview.GuzhangTF.text.length > 50){
            [self showAlert:@"温馨提示" message:@"主要故障超过限定字数" actionWithTitle:@"我知道了"];
    }else{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"提交中...";
        self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:FeedBackUpURL parameters:premert constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i<self.masview.imageArray.count; i++) {
            
            NSData *imageData =UIImageJPEGRepresentation(self.masview.imageArray[i], 0.5);
            CGFloat dataBytes = imageData.length/1000.0;
            CGFloat maxQuality = 0.5f;
            CGFloat lastData = dataBytes;
            while (dataBytes > 300 && maxQuality > 0.1f) {
                maxQuality = maxQuality - 0.1f;
                imageData = UIImageJPEGRepresentation(self.masview.imageArray[i], maxQuality);
                dataBytes = imageData.length / 1000.0;
                if (lastData == dataBytes) {
                    break;
                }else{
                    lastData = dataBytes;
                }
            }
            //NSLog(@"%f",dataBytes);
            //if (dataBytes<300 || dataBytes == 300) {
            
            NSString *fileName = [NSString  stringWithFormat:@"image%d.jpg", i];
            [formData appendPartWithFileData:imageData name:@"GZLR" fileName:fileName mimeType:@"image/jpeg"];
            // }
        }

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //NSLog(@"%@",dic);
        NSInteger status = [dic[@"status"]integerValue];
        //NSLog(@"%ld",status);
        if (status == 1) {
            //延时操作
            [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"提交成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                
            } completion:^(BOOL finished) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500 || status == 0) {
            [self showAlert:@"提交失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
    }
}
//massview取消提交代理方法
- (void)RevokeClick:(UIButton *)sender{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否确定退出当前页面" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)backClick{
    

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否确定退出当前页面" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
